const api = require('../../../ws_micro_shop/utils/api.js');
const tools = require('../../../ws_micro_shop/utils/getuserinfo.js');
const app = getApp();
const { module: moduleName } = app.siteInfo;
const util = app.util;

let timer = null;

function secondToTimeStr(second) {
  if (second < 60) {
    let _s = second;
    // return '00:00:' + (_s < 10 ? '0' + _s : _s);
    return  {
      h: '00',
      m: '00',
      s: _s < 10 ? '0' + _s : _s,
    };
      '00:00:' + (_s < 10 ? '0' + _s : _s);
  }
  if (second < 3600) {
    let _m = parseInt(second / 60, 10);
    let _s = second % 60;
    // return '00:' + (_m < 10 ? '0' + _m : _m) + ':' + (_s < 10 ? '0' + _s : _s);
    return {
      h: '00',
      m: _m < 10 ? '0' + _m : _m,
      s: _s < 10 ? '0' + _s : _s,
    };
  }
  if (second >= 3600) {
    let _h = parseInt(second / 3600, 10);
    let _m = parseInt((second % 3600) / 60, 10);
    let _s = second % 60;
    // return (_h < 10 ? '0' + _h : _h) + ':' + (_m < 10 ? '0' + _m : _m) + ':' + (_s < 10 ? '0' + _s : _s);
    return {
      h: _h < 10 ? '0' + _h : _h,
      m: _m < 10 ? '0' + _m : _m,
      s: _s < 10 ? '0' + _s : _s,
    };
  }
}

Page({
  data: {
    time_list: null,
    goods_list: [],
    page: 1,
    loading_more: false,
    showloading: true,
    listHeight: 600,
    unit: '',
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    goodStatus: 0,
    abnorData: {
      imgSrc: app.imgUrl + 'goods_empty.png',
      text: '暂无秒杀商品',
    },
    imgUrl: app.imgUrl,
  },
  onLoad(options) {
    let that = this;
    let opts = options || {};
    this.setData({
      orgPrice: app.ws_micro_shop_globalData.orgPrice,
      useTabbar: that.data.useTabbar && app.getTabBarStatus(),
    });
    app.tabbarindex = opts.tabbarindex ? opts.tabbarindex - 0 : app.tabbarindex;
    if (options && options.shopid) {
      app.ws_micro_shop_globalData.shopid = options.shopid;
    }
    app.pageOnLoad(this);
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    const query = wx.createSelectorQuery();
    query.select('.top-bar').boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec(function (res) {
      let windowHeight =wx.systemInfo.windowHeight;
      let height = res && res[0] && res[0].height || 0;
      that.setData({
        listHeight: windowHeight - height,
      });
    });
    let userinfo = wx.getStorageSync('user_info');
    if (userinfo) {
      Number(userinfo.info) === 0 && tools.onGetInfo(this, userinfo.auth_mode);
      util.prepareBindInfo(options, moduleName, that);
    } else {
      app.ws_micro_shoplogin().then(res => {
        userinfo = wx.getStorageSync('user_info');
        Number(userinfo.info) === 0 && tools.onGetInfo(that, userinfo.auth_mode);
        util.prepareBindInfo(options, moduleName, that);
      });
    }
    this.setData({ 
      opts,
      useTabbar: that.data.useTabbar && app.getTabBarStatus(),
    });
    this.loadData();
  },
  loadData() {
    let page = this;
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.miaosha.list,
      success: function (res) {
        wx.hideLoading();
        if (res.code === 0) {
          if (res.data.list.length === 0) {
            wx.showModal({
              content: '今日暂无秒杀商品',
              showCancel: false,
              confirmText: '好的',
              success: function (e) {
                if (e.confirm) {
                  app.util.navigateTo('/ws_micro_shop/pages/index/index');
                }
              },
            });
            return;
          }

          let list = res.data.list;
          let f = list.every(function (item) {
            return item.active == false;
          });
          if (f) {
            list[list.length-1].active = true;
          }
          page.setData({
            time_list: list,
          });
          page.topBarScrollCenter();
          page.setTimeOver();
        }
      },
    });
  },
  setTimeOver() {
    let page = this;
    function _init() {
      for (let i in page.data.time_list) {
        if ({}.hasOwnProperty.call(page.data.time_list, i)) {

          let startTime = page.data.time_list[i].begin_time;
          let endTime = page.data.time_list[i].end_time;
          let nowTime = page.data.time_list[i].now_time;

          let begin_time_over = startTime - nowTime;
          let end_time_over = endTime - nowTime;
          begin_time_over = begin_time_over > 0 ? begin_time_over : 0;
          end_time_over = end_time_over > 0 ? end_time_over : 0;

          // 更改当前数据的 status状态  status_text文字
          if(startTime - nowTime > 0){ 
            page.data.time_list[i]['status'] = 2;
            page.data.time_list[i]['status_text'] = '即将开始';
          }
          if(nowTime - startTime >= 0 && endTime - nowTime > 0){
            page.data.time_list[i]['status'] = 1;
            page.data.time_list[i]['status_text'] = '进行中';
          }
          if(nowTime - endTime >= 0){
            page.data.time_list[i]['status'] = 0;
            page.data.time_list[i]['status_text'] = '已结束';
          }
          
          page.data.time_list[i]['begin_time_over'] = secondToTimeStr(begin_time_over);
          page.data.time_list[i]['end_time_over'] = secondToTimeStr(end_time_over);
          page.data.time_list[i].now_time = page.data.time_list[i].now_time + 1;
        }
      }
      let timeList = page.data.time_list;
      // if(page.data.goods_list && page.data.goods_list.length > 0){
      //   for(let i = 0; i < timeList.length; i++){
      //     if ((timeList[i].custom_time && timeList[i].custom_time != '' && timeList[i].custom_time == page.data.goods_list[0].custom_time) || timeList[i].start_time == page.data.goods_list[0].start_time){
      //       page.setData({
      //         goodStatus: timeList[i].status,
      //       })
      //     }
      //   }
      // }
      page.setData({
        time_list: page.data.time_list,
      });
    }
    _init();
    timer = setInterval(function () {
      _init();
    }, 1000);
  },
  topBarScrollCenter() {
    let index = 0;
    for (let i in this.data.time_list) {
      if (this.data.time_list[i].active) {
        index = i;
        break;
      }
    }
    this.setData({
      top_bar_scroll: (index - 1) * 76,
      index,
      oldindex: index,
    });
    this.loadGoodsList(false);
  },
  topBarItemClick(e) {
    let index = e.currentTarget.dataset.index;
    let { oldindex } = this.data;
    if (Number(oldindex) === Number(index)) return;
    for (let i in this.data.time_list) {
      if (index === Number(i)) {
        this.data.time_list[i].active = true;
      } else {
        this.data.time_list[i].active = false;
      }
    }
    this.setData({
      time_list: this.data.time_list,
      loading_more: false,
      page: 1,
      showloading: true,
      goodStatus: 0,
      oldindex: index,
    });
    this.topBarScrollCenter();
  },

  loadGoodsList(load_more) {
    let page = this;
    let time = false;
    let { time_list, index } = page.data;
    if (time_list.some(item => item.active === true)) {
      for (let i in time_list) {
        if (time_list[i].active) {
          // 添加秒杀自定义字段 custom_time 处理
          time = (time_list[i].custom_time && time_list[i].custom_time != '') ? time_list[i].custom_time : time_list[i].start_time;
          page.setData({
            time,
          });
          break;
        }
      }
    } else {
      time_list.length > 0
        && (time = (time_list[0].custom_time && time_list[0].custom_time != '') ? time_list[0].custom_time : time_list[0].start_time, true)
        && page.setData({
          time,
        });
    }
    if (time) {
      if (!load_more) {
        page.setData({
          goods_list: [],
        });
      } else {
        page.setData({
          loading_more: true,
        });
      }
      wx.showLoading({
        title: '加载中...',
        mask: true,
      });
      app.ws_micro_shoprequest({
        url: api.miaosha.goods_list,
        data: {
          time,
          page: page.data.page,
        },
        success: function (res) {
          wx.hideLoading();
          if (res.code === 0) {
            if (load_more) {
              page.data.goods_list = page.data.goods_list.concat(res.data.list);
            } else {
              page.data.goods_list = res.data.list;
            }
            page.setData({
              loading_more: false,
              goods_list: page.data.goods_list,
              goodStatus: time_list[index].status,
              showloading: false,
              page: (!res.data.list || res.data.list.length === 0) ? -1 : (page.data.page + 1),
            });
          }
        },
      });
    } else {
      wx.showToast({
        title: '今日秒杀活动已结束啦,明日趁早再来吧',
        icon: 'none',
        duration: 3000,
        success: function () {
          page.setData({
            showloading: false,
          });
        },
      });
    }
  },
  loadMoreList() {
    if (this.data.page === -1) {
      return;
    }
    this.loadGoodsList(true);
  },
  onShareAppMessage() {
    let path = '/ws_micro_shop/pages/miaosha/miaosha?tabbarindex=' + app.tabbarindex + '&shopid=' + app.ws_micro_shop_globalData.shopid;
    path = util.spliceSharePath(path, '4', moduleName);
    return {
      path,
    };
  },
  onShareTimeline() {
    return {
      title: '',
      imageUrl: '',
      query: 'tabbarindex=' + app.tabbarindex + '&shopid=' + app.ws_micro_shop_globalData.shopid
    }
  },
  // onHide() {
  //   timer && clearInterval(timer);
  //   util.sendBindInfo(this.data);
  // },
  onUnload() {
    timer && clearInterval(timer);
    util.sendBindInfo(this.data);
  },
  collectFormId(e) {
    app.collectFormId(e);
  },
});
